/* Copyright(c) 2010- Siro-info Co.(http://www.siro-info.com)
 * All rights reserved.
 */
package com.siro.pm.model.provider;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.siro.pm.I18nManager;
import com.siro.pm.model.UserAttendance;
import com.siro.pm.utils.PmUtils;
import com.vaadin.addon.calendar.event.CalendarEvent;
import com.vaadin.addon.calendar.event.CalendarEventProvider;

/**
 * Class Declaration:
 * 
 * @version v1.0
 * @since AttendanceProvider.java v1.0
 */
public class AttendanceProvider implements CalendarEventProvider {

	private static final long serialVersionUID = -3655982234130426761L;

	public static String ATTENDANCE_PROPERTY_STATUS = I18nManager
			.getMessage("attendance.status");
	public static String ATTENDANCE_PROPERTY_DESC = I18nManager
			.getMessage("attendance.desc");
	public static String ATTENDANCE_PROPERTY_WHERE = I18nManager
			.getMessage("attendance.where");
	public static String ATTENDANCE_PROPERTY_BANKNAME = I18nManager
			.getMessage("attendance.bankname");

	public static String[] ATTENDANCE_STATUS_DATA = {
			I18nManager.getMessage("attendance.work"),
			I18nManager.getMessage("attendance.rest"),
			I18nManager.getMessage("attendance.travel"),
			I18nManager.getMessage("attendance.personalLeave"),
			I18nManager.getMessage("attendance.sickLeave"), };

	private String userName;
	private Date lastStartDate, lastEndDate;

	private List<CalendarEvent> attendances = new ArrayList<CalendarEvent>();

	public AttendanceProvider() {
	}

	public void addEvent(CalendarEvent attendance) {
		if (!containsEvent(attendance)) {
			attendances.add(attendance);
		}
	}

	public boolean containsEvent(CalendarEvent event) {
		return attendances.contains(event);
	}

	public boolean containsAttendance(Date date) {
		for (CalendarEvent attendance : attendances) {
			if (PmUtils.getSDF().format(attendance.getStart())
					.equals(PmUtils.getSDF().format(date))) {
				return true;
			}
		}
		return false;
	}

	public List<CalendarEvent> getEvents(Date startDate, Date endDate) {
		if (attendances.isEmpty()
				|| (lastStartDate != null && !lastStartDate.equals(startDate)
						&& lastEndDate != null && !lastEndDate.equals(endDate))) {
			List<UserAttendance> userAttendances = UserAttendance
					.getUserAttendanceByDateAndUser(userName, PmUtils.getSDF()
							.format(startDate), PmUtils.getSDF()
							.format(endDate));
			for (UserAttendance userAttendance : userAttendances) {
				addEvent(userAttendance.toAttendance());
			}
			lastStartDate = startDate;
			lastEndDate = endDate;
		}
		return attendances;
	}

	public List<CalendarEvent> getCurrentAllEvents() {
		return attendances;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

}
